package com.example.mybatis.controller;

import com.example.mybatis.pojo.UserT;
import com.example.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/addUser")
    public ModelAndView addUser(UserT userT) {

        try {
            this.userService.addUser(userT);
        } catch (Exception e) {
            return new ModelAndView("error");
        }

        return new ModelAndView("redirect:/success");
    }

    @GetMapping("getAllUsers")
    public ModelAndView getAllUsers() {
        ModelAndView modelAndView = new ModelAndView("/userList");
        List<UserT> userList = this.userService.getAllUsers();
        modelAndView.addObject("userList", userList);
        /**
         * 这样放入list之后，Thymeleaf解析不到该key
         * modelAndView.addObject(userList);
         */
        return modelAndView;
    }

    @GetMapping("/preModifyUser/{userName}")
    public String preModifyUser(@PathVariable String userName, Model model){
        UserT user = this.userService.getUserByUserName(userName);
        model.addAttribute("user",user);
        return "/preModifyUser";
    }

    @PostMapping("/updateUser")
    public String updateUser(UserT user){
        try {
            this.userService.updateUser(user);
        }catch (Exception e){
            return "error";
        }
        return "redirect:/success";
    }

    @GetMapping("/deleteUser/{userName}")
    public String deleteUser(@PathVariable String  userName){


        try {
            this.userService.deleteUser(userName);
        }catch (Exception e){
            e.printStackTrace();
            return "/error";
        }
        return "redirect:/success";
    }
}
